﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using System.Web.UI.WebControls;
using Beeldbankmvc.Code;
using Beeldbankmvc.Models;
using Elmah;

namespace Beeldbankmvc.Helpers
{
    [HandleErrorWithELMAH]
    public static class Tools
    {
        public static void CheckDir(string directoryName)
        {
            string[] subDirectories = directoryName.Replace("/", "\\").Split('\\');
            string locationDownloadTo = "";
            bool isUNCPath = false;

            // Added to allow for UNC directories that start with "\\"
            if (directoryName.StartsWith("\\\\"))
            {
                locationDownloadTo = "\\\\";
                isUNCPath = true;
            }

            for (int i = 0; i < subDirectories.Length; i++)
            {
                if (subDirectories[i].Length != 0)
                {
                    locationDownloadTo += subDirectories[i] + "\\";

                    if (isUNCPath)
                    {
                        // Only when the first part of the UNC share is present in de path,
                        // the check if this directory exists must be executed
                        if ((locationDownloadTo.Contains("$\\")) && (!locationDownloadTo.EndsWith("$\\")))
                        {
                            if (!System.IO.Directory.Exists(locationDownloadTo))
                                System.IO.Directory.CreateDirectory(locationDownloadTo);
                        }
                        else
                        {
                            if (i > 3)
                            {
                                try
                                {
                                    if (!System.IO.Directory.Exists(locationDownloadTo))
                                        System.IO.Directory.CreateDirectory(locationDownloadTo);
                                }
                                catch (Exception ex)
                                {
                                    // Log exception
                                    ex.Data.Add("locationDownloadTo", locationDownloadTo);
                                    ex.Data["locationDownloadTo"] = locationDownloadTo;
                                    var context = HttpContext.Current;
                                    ErrorLog.GetDefault(context).Log(new Error(ex, context));
                                }
                            }
                        }
                    }
                    else
                        if (!System.IO.Directory.Exists(locationDownloadTo))
                            System.IO.Directory.CreateDirectory(locationDownloadTo);
                }
            }
        }
        
        public static string originalFileURL(BEELDBANK_MEDIAOBJECT mediaObject, string extension)
        {
            int mapNumber = Convert.ToInt32(mediaObject.FileNummer) / Convert.ToInt32(ConfigurationManager.AppSettings["MaxFotosInDirectory"]);

            return ConfigurationManager.AppSettings["MediaObjectLibraryFile"] + "/" + mapNumber.ToString() + "/" + mediaObject.FileNummer + extension;
        }
        
        public static string originalMediaURL(BEELDBANK_MEDIAOBJECT mediaObject, string extension)
        {
            int mapNumber = Convert.ToInt32(mediaObject.FileNummer) / Convert.ToInt32(ConfigurationManager.AppSettings["MaxFotosInDirectory"]);

            string fileName = "";
            if (mediaObject.TypeId == (int)Mediatypes.MediaTypes.video_animation)
            {
                fileName = ConfigurationManager.AppSettings["MediaObjectLibraryVideo"] + "/" + mapNumber.ToString() + "/" + mediaObject.FileNummer;
            }
            else if (mediaObject.TypeId == (int)Mediatypes.MediaTypes.map_illustration)
            {
                fileName = ConfigurationManager.AppSettings["MediaObjectLibraryFoto"] + "/" + mapNumber.ToString() + "/" + mediaObject.FileNummer + extension;
            }
            else
            {
                fileName = ConfigurationManager.AppSettings["MediaObjectLibraryFoto"] + "/" + mapNumber.ToString() + "/" + mediaObject.FileNummer + extension;
            }
            return fileName;
        }

        public static string writeMovieDownloadLink(BEELDBANK_MEDIAOBJECT mediaObject, string extension)
        {
            StringBuilder retString = new StringBuilder();

            string description = "";
            string icon = "";
            string type = "";

            switch(extension)
            {
                case "mp4":
                    description = "Video voor Apple Quicktime Player";
                    icon = "qt-ikoon.gif";
                    type = "video";
                    break;
                case "m4v":
                    description = "Video voor Apple Quicktime Player";
                    icon = "qt-ikoon.gif";
                    type = "video";
                    break;
                case "mov":
                    description = "Video voor Apple Quicktime Player";
                    icon = "qt-ikoon.gif";
                    type = "video";
                    break;
                case "HQ mp4":
                    description = "Video voor Apple Quicktime Player (hoge kwaliteit)";
                    icon = "qt-ikoon.gif";
                    extension = "mp4";
                    type = "HQ video";
                    break;
                case "mpg":
                    description = "Video voor Windows Media Player (MPEG-1)";
                    icon = "wmv-ikoon.gif";
                    type = "video";
                    break;
                case "mpeg":
                    description = "Video voor Windows Media Player (MPEG-2)";
                    icon = "wmv-ikoon.gif";
                    type = "video";
                    break;
                case "wmv":
                    description = "Video voor Windows Media Player";
                    icon = "wmv-ikoon.gif";
                    type = "video";
                    break;
                case "3gp":
                    description = "Video voor mobiel gebruik";
                    icon = "3gp-ikoon.gif";
                    type = "video";
                    break;
                case "mp3":
                    description = "Audiobeschrijving";
                    icon = "mp3-ikoon.gif";
                    type = "audio";
                    break;
                case "srt":
                    description = "Ondertitelingsbestand";
                    icon = "srt-ikoon.gif";
                    type = "Ondertiteling";
                    break;
                case "xml":
                    description = "Ondertitelingsbestand";
                    icon = "srt-ikoon.gif";
                    type = "Ondertiteling";
                    break;
                case "c srt":
                    description = "Caption bestand";
                    icon = "srt-ikoon.gif";
                    type = "Caption";
                    extension = "srt";
                    break;
            }

            int mapNumber = Convert.ToInt32(mediaObject.FileNummer) / Convert.ToInt32(ConfigurationManager.AppSettings["MaxFotosInDirectory"]);
            
            string filePath = "";
            switch (type)
            {
                case "HQ video":
                    filePath = ConfigurationManager.AppSettings["VideoArchive"] + "\\" + mapNumber.ToString() + "\\" + mediaObject.FileNummer + "_HQ." + extension;
                    break;
                case "Caption":
                    filePath = ConfigurationManager.AppSettings["VideoArchive"] + "\\" + mapNumber.ToString() + "\\" + mediaObject.FileNummer + "_C." + extension;
                    break;
                default:
                    filePath = ConfigurationManager.AppSettings["VideoArchive"] + "\\" + mapNumber.ToString() + "\\" + mediaObject.FileNummer + "." + extension;
                    break;
            }
            
            FileInfo movieFile = new FileInfo(filePath);
            if (movieFile.Exists)
            {
                switch (type)
                {
                    case "HQ video":
                        retString.AppendLine("<a href=\"" + originalMediaURL(mediaObject, "") + "_HQ." + extension + "\">" + description);
                        break;
                    case "Caption":
                        retString.AppendLine("<a href=\"" + originalMediaURL(mediaObject, "") + "_C." + extension + "\">" + description);
                        break;
                    default:
                        retString.AppendLine("<a href=\"" + originalMediaURL(mediaObject, "") + "." + extension + "\">" + description);
                        break;
                }
                retString.AppendLine("<img src=\"../../Content/images/OverheidsMediaPlayer/" + icon + "\" alt=\"\" /> " + extension + ", " + String.Format("{0:0.##}", Convert.ToDecimal(movieFile.Length) / 1000000) + " MB");
                retString.AppendLine("</a>");
                retString.AppendLine("<br />");
            }

            return retString.ToString();
        }

        public static string writeFileSize(BEELDBANK_MEDIAOBJECT mediaObject, bool showBrackets)
        {
            StringBuilder retString = new StringBuilder();

            int mapNumber = Convert.ToInt32(mediaObject.FileNummer) / Convert.ToInt32(ConfigurationManager.AppSettings["MaxFotosInDirectory"]);

            string directory = ConfigurationManager.AppSettings["FileArchive"] + "\\" + mapNumber.ToString() + "\\";

            if (Directory.Exists(directory))
            {
                string[] files = Directory.GetFiles(directory, mediaObject.FileNummer + ".*", SearchOption.TopDirectoryOnly);

                // Get the first file
                foreach (string file in files)
                {
                    FileInfo fotoFile = new FileInfo(file);
                    if (fotoFile.Exists)
                    {
                        if (showBrackets)
                            retString.AppendLine("(" + String.Format("{0:0.##}", Convert.ToDecimal(fotoFile.Length) / 1000000) + " MB)");
                        else
                            retString.AppendLine(String.Format("{0:0.##}", Convert.ToDecimal(fotoFile.Length) / 1000000) + " MB ");
                    }
                    break;
                }
            }
            return retString.ToString();
        }

        public static string writeImageSize(BEELDBANK_MEDIAOBJECT mediaObject, bool showBrackets, string extension)
        {
            StringBuilder retString = new StringBuilder();

            int mapNumber = Convert.ToInt32(mediaObject.FileNummer) / Convert.ToInt32(ConfigurationManager.AppSettings["MaxFotosInDirectory"]);

            string filePath = ConfigurationManager.AppSettings["FotoArchive"] + "\\" + mapNumber.ToString() + "\\" + mediaObject.FileNummer + extension;

            FileInfo imageFile = new FileInfo(filePath);
            if (imageFile.Exists)
            {
                if (showBrackets)
                    retString.AppendLine("(" + String.Format("{0:0.##}", Convert.ToDecimal(imageFile.Length) / 1000000) + " MB)");
                else
                    retString.AppendLine(String.Format("{0:0.##}", Convert.ToDecimal(imageFile.Length) / 1000000) + " MB");
            }

            return retString.ToString();
        }

        public static string writeMovieJWPlayer(BEELDBANK_MEDIAOBJECT mediaObject, string extension)
        {
            StringBuilder retString = new StringBuilder();

            string javascriptStart = "";
            string javascriptEnd = "";
            string filePath = "";

            int mapNumber = Convert.ToInt32(mediaObject.FileNummer) / Convert.ToInt32(ConfigurationManager.AppSettings["MaxFotosInDirectory"]);

            var Url = new UrlHelper(((MvcHandler)HttpContext.Current.Handler).RequestContext);
                    
            switch (extension)
            {
                case "jpg":
                    filePath = ConfigurationManager.AppSettings["VideoArchive"] + "/" + mapNumber.ToString() + "/" + mediaObject.FileNummer + "." + extension;
                    FileInfo jpgFile = new FileInfo(filePath);
                    if (jpgFile.Exists)
                        retString.AppendLine(@"image: """ + originalMediaURL(mediaObject, "") + @".jpg"",");
                    break;
                case "layout":
                   // retString.Append("'logo': '" + Url.Content("~/Content/images/logos/Rijksoverheid.png") + "','logo.margin':0,'logo.position':'top-left',");
                   // retString.Append("'controlbar': 'bottom',");
                    if (!String.IsNullOrEmpty(mediaObject.Montage) && mediaObject.Montage.Contains("16x9"))
                        retString.Append("width: 400,height: 249,"); // 400 : 225+24
                    else
                        retString.Append("width: 400,height: 324,"); // 400 : 300+24
                    break;
                case "layoutsmall":
                   // retString.Append("'controlbar': 'bottom',");
                    if (!String.IsNullOrEmpty(mediaObject.Montage) && mediaObject.Montage.Contains("16x9"))
                        retString.Append("width: 300,height: 193,"); // 300 : 169+24
                    else
                        retString.Append("width: 300,height: 249,"); // 300 : 225+24
                    break;
                case "caption":
                    filePath = ConfigurationManager.AppSettings["VideoArchive"] + "/" + mapNumber.ToString() + "/" + mediaObject.FileNummer + ".srt";
                    FileInfo srtFile = new FileInfo(filePath);
                    if (srtFile.Exists)
                        retString.AppendLine(@"file: """ + originalMediaURL(mediaObject, "") + @".srt"",");
                    break;

                case "accessibility":
                    //filePath = ConfigurationManager.AppSettings["VideoArchive"] + "/" + mapNumber.ToString() + "/" + mediaObject.FileNummer + ".xml";
                    //FileInfo srtFile = new FileInfo(filePath);
                    //if (srtFile.Exists)
                    //    retString.AppendLine("'captions.file': '" + originalMediaURL(mediaObject, "") + ".xml',");
                    //else
                    //{
                    //    filePath = ConfigurationManager.AppSettings["VideoArchive"] + "/" + mapNumber.ToString() + "/" + mediaObject.FileNummer + ".srt";
                    //    srtFile = new FileInfo(filePath);
                    //    if (srtFile.Exists)
                    //        retString.AppendLine("'captions.file': '" + originalMediaURL(mediaObject, "") + ".srt',");
                    //}

                    filePath = ConfigurationManager.AppSettings["VideoArchive"] + "/" + mapNumber.ToString() + "/" + mediaObject.FileNummer + ".srt";
                    srtFile = new FileInfo(filePath); // FileInfo 

                    filePath = ConfigurationManager.AppSettings["VideoArchive"] + "/" + mapNumber.ToString() + "/" + mediaObject.FileNummer + ".mp3";
                    FileInfo audioFile = new FileInfo(filePath);
                    if (audioFile.Exists)
                        retString.AppendLine("'audiodescription.file': '" + originalMediaURL(mediaObject, "") + ".mp3',");

                    if (audioFile.Exists || srtFile.Exists)
                    {
                        string tmpString = "'plugins': '";
                        if (srtFile.Exists) tmpString += Url.Content("~/Content/flash/captions-1.swf");
                        if (audioFile.Exists && srtFile.Exists) tmpString += ",";
                        if (audioFile.Exists) tmpString += Url.Content("~/Content/flash/audiodescription-2.swf");
                        tmpString += "',";
                        retString.AppendLine(tmpString);
                    }
                    
                    break;
                case "movievoicebutton":
                        filePath = ConfigurationManager.AppSettings["VideoArchive"] + "/" + mapNumber.ToString() + "/" + mediaObject.FileNummer + "_voice" + ".mp4";
                        FileInfo movieFileVoice = new FileInfo(filePath);
                        if (movieFileVoice.Exists)
                        {
                             retString.AppendLine("jwplayer('mediaplayer').addButton('" + AppHelper.getContent("~/Content/images/novoice.png") + "', 'Gesproken tekst toevoegen', function(){addVoice();}, 'voiceaudio');");
                        }
                    break;

                case "movies":
                    javascriptStart = "file: \"";
                    bool moviefound = false;
                    javascriptEnd = ".mp4\", ";
                    filePath = ConfigurationManager.AppSettings["VideoArchive"] + "/" + mapNumber.ToString() + "/" + mediaObject.FileNummer + ".mp4";
                    FileInfo movieFile = new FileInfo(filePath);
                    if (movieFile.Exists)
                    {
                        if (moviefound)                            
                            retString.AppendLine(", "+ javascriptStart + originalMediaURL(mediaObject, "") + javascriptEnd);
                        else
                        {
                            moviefound = true;
                            retString.AppendLine(javascriptStart + originalMediaURL(mediaObject, "") + javascriptEnd);
                        }
                    }
                    break;
                case "moviesvoice":
                    javascriptStart = "file: \"";
                    moviefound = false;
                    javascriptEnd = "_voice.mp4\" ";
                    filePath = ConfigurationManager.AppSettings["VideoArchive"] + "/" + mapNumber.ToString() + "/" + mediaObject.FileNummer + "_voice" + ".mp4";
                    FileInfo movieFile2 = new FileInfo(filePath);
                    if (movieFile2.Exists)
                    {
                        if (moviefound)
                            retString.AppendLine(javascriptStart + originalMediaURL(mediaObject, "") + javascriptEnd);
                        else
                        {
                            moviefound = true;
                            retString.AppendLine(javascriptStart + originalMediaURL(mediaObject, "") + javascriptEnd);
                        }
                    }
                    break;
            }

            return retString.ToString();
        }

        public static bool hasVideo(BEELDBANK_MEDIAOBJECT mediaObject)
        {
            int mapNumber = Convert.ToInt32(mediaObject.FileNummer) / Convert.ToInt32(ConfigurationManager.AppSettings["MaxFotosInDirectory"]);

            String extension = "";
            for (int i = 1; i < 6; i++)
            {
                switch (i)
                {
                    case 1:
                        extension = "flv";
                        break;
                    case 2:
                        extension = "mp4";
                        break;
                    case 3:
                        extension = "m4v";
                        break;
                    case 4:
                        extension = "mov";
                        break;
                    case 5:
                        extension = "3gp";
                        break;
                }
                String filePath = ConfigurationManager.AppSettings["VideoArchive"] + "/" + mapNumber.ToString() + "/" + mediaObject.FileNummer + "." + extension;
                FileInfo movieFile = new FileInfo(filePath);
                if (movieFile.Exists)
                {
                    return true;
                }
            }

            return false;
        }

        public static bool hasFullImage(BEELDBANK_MEDIAOBJECT mediaObject)
        {
            int mapNumber = Convert.ToInt32(mediaObject.FileNummer) / Convert.ToInt32(ConfigurationManager.AppSettings["MaxFotosInDirectory"]);
            string jpgFilePath = ConfigurationManager.AppSettings["FotoArchive"] + "\\" + mapNumber.ToString() + "\\" + mediaObject.FileNummer + ".jpg";
            string tifFilePath = ConfigurationManager.AppSettings["FotoArchive"] + "\\" + mapNumber.ToString() + "\\" + mediaObject.FileNummer + ".tif";

            FileInfo jpgImageFile = new FileInfo(jpgFilePath);
            FileInfo tifImageFile = new FileInfo(tifFilePath);
            if (jpgImageFile.Exists || tifImageFile.Exists)
                return true;
            else
                return false;
        }

        public static string getPreviewImage(BEELDBANK_MEDIAOBJECT mediaObject)
        {
            StringBuilder retString = new StringBuilder();

            string fotoTypeKey = "FotoArchive";

            int mapNumber = Convert.ToInt32(mediaObject.FileNummer) / Convert.ToInt32(ConfigurationManager.AppSettings["MaxFotosInDirectory"]);
            string jpgFilePath = ConfigurationManager.AppSettings[fotoTypeKey] + "\\" + mapNumber.ToString() + "\\" + mediaObject.FileNummer + "_[600].jpg";

            FileInfo jpgImageFile = new FileInfo(jpgFilePath);
            if (jpgImageFile.Exists)
                retString.AppendLine(jpgFilePath);

            return retString.ToString();
        }

        public static string getThemeImage(CollectionModel collection)
        {
            StringBuilder retString = new StringBuilder();

            string jpgFilePath = ConfigurationManager.AppSettings["appData"] + "\\" + collection.Id + ".jpg";

            FileInfo jpgImageFile = new FileInfo(jpgFilePath);
            if (jpgImageFile.Exists)
                retString.AppendLine(jpgFilePath);

            return retString.ToString();
        }

        public static string getFullImage(BEELDBANK_MEDIAOBJECT mediaObject)
        {
            StringBuilder retString = new StringBuilder();

            string fotoTypeKey = "FotoArchive";

            int mapNumber = Convert.ToInt32(mediaObject.FileNummer) / Convert.ToInt32(ConfigurationManager.AppSettings["MaxFotosInDirectory"]);
            string jpgFilePath = ConfigurationManager.AppSettings[fotoTypeKey] + "\\" + mapNumber.ToString() + "\\" + mediaObject.FileNummer + ".jpg";
            string tifFilePath = ConfigurationManager.AppSettings[fotoTypeKey] + "\\" + mapNumber.ToString() + "\\" + mediaObject.FileNummer + ".tif";

            FileInfo jpgImageFile = new FileInfo(jpgFilePath);
            FileInfo tifImageFile = new FileInfo(tifFilePath);
            if (jpgImageFile.Exists)
                retString.AppendLine( "<img src=\"" + originalMediaURL(mediaObject, ".jpg") +  "\" alt=\"" + mediaObject.Omschrijving + "\" />");
            else
                if (tifImageFile.Exists)
                    retString.AppendLine("<img src=\"" + originalMediaURL(mediaObject, ".tif") + "\" alt=\"" + mediaObject.Omschrijving + "\" />");

            return retString.ToString(); 
        }

        public static string getFullImageDownloadLink(BEELDBANK_MEDIAOBJECT mediaObject)
        {
            StringBuilder retString = new StringBuilder();

            int mapNumber = Convert.ToInt32(mediaObject.FileNummer) / Convert.ToInt32(ConfigurationManager.AppSettings["MaxFotosInDirectory"]);

            string directory = ConfigurationManager.AppSettings["FotoArchive"] + "\\" + mapNumber.ToString() + "\\";

            if (Directory.Exists(directory))
            {
                string[] files = Directory.GetFiles(directory, mediaObject.FileNummer + ".*", SearchOption.TopDirectoryOnly);

                // Get the list of files
                foreach (string file in files)
                {
                    string[] pathParts = file.Split('.');
                    string extension = "." + pathParts[pathParts.Length - 1];

                    // Get the next file
                    FileInfo fotoFile = new FileInfo(file);
                    if (fotoFile.Exists)
                        retString.AppendLine("<a href=\"" + originalMediaURL(mediaObject, extension) + "\" title=\"" +  AppHelper.convertHtmlStringToAltTag(mediaObject) + "\" >Download gratis de digitale foto " + writeImageSize(mediaObject, true, extension) + "</a><br />");
                }
            }
            return retString.ToString();
        }

        public static bool hasFullDownload(BEELDBANK_MEDIAOBJECT mediaObject)
        {
            int mapNumber = Convert.ToInt32(mediaObject.FileNummer) / Convert.ToInt32(ConfigurationManager.AppSettings["MaxFotosInDirectory"]);

            string directory = ConfigurationManager.AppSettings["FileArchive"] + "\\" + mapNumber.ToString() + "\\";

            if (Directory.Exists(directory))
            {
                string[] files = Directory.GetFiles(directory, mediaObject.FileNummer + ".*", SearchOption.TopDirectoryOnly);

                if (files.Count() >= 1)
                {
                    // Get the first file
                    FileInfo fotoFile = new FileInfo(files[0]);
                    if (fotoFile.Exists)
                        return true;
                    else
                        return false;
                }
                else
                    return false;
            }
            else
                return false;
        }
        
        public static string getFullDownloadLink(BEELDBANK_MEDIAOBJECT mediaObject)
        {
            StringBuilder retString = new StringBuilder();

            int mapNumber = Convert.ToInt32(mediaObject.FileNummer) / Convert.ToInt32(ConfigurationManager.AppSettings["MaxFotosInDirectory"]);

            string directory = ConfigurationManager.AppSettings["FileArchive"] + "\\" + mapNumber.ToString() + "\\";

            if (Directory.Exists(directory))
            {
                string[] files = Directory.GetFiles(directory, mediaObject.FileNummer + ".*", SearchOption.TopDirectoryOnly);

                // Get the list of files
                foreach (string file in files)
                {
                    string[] pathParts = file.Split('.');
                    string extension = "." + pathParts[pathParts.Length - 1];

                    // Get next file
                    FileInfo bronFile = new FileInfo(file);
                    if (bronFile.Exists)
                        retString.AppendLine("<a href=\"" + originalFileURL(mediaObject, extension) + "\" title=\"" + mediaObject.Omschrijving + "\" >Download bronbestand " + writeFileSize(mediaObject, true) + "</a><br />");
                }
            }
            return retString.ToString();
        }
        
        public static string getMaxLengthVersion(String originalText, int maxLength)
        {
            if (originalText.Length > maxLength)
                originalText = originalText.Substring(0, maxLength - 3) + "...";

            return originalText;
        }

        public static string getCounterView()
        {
            return ConfigurationManager.AppSettings["CounterView"];
        }
        
        public static string writeRoles(String username)
        {
            // Bind these checkboxes to the User's own set of roles.
            string[] userRoles = Roles.GetRolesForUser(username);
            string retString = "" ;
            foreach (string role in userRoles)
                retString = retString + role + ", ";

            if (!retString.Equals(""))
                return retString.Substring(0, retString.Length - 2);
            else
                return retString;
        }
        
        public static List<String> generateYearList()
        {
            List<String> yearlist = new List<string>();
            for (int i = 1900; i < 2020; i++)
                yearlist.Add(i.ToString());

            return yearlist;
        }

    }
}